import 'dart:async';
import 'dart:developer';

import 'package:flutter/material.dart';

/// 1. 基本使用
/// 2. 事件订阅
/// 参考资料
class StreamSubscriptionDemoHome extends StatefulWidget {
  const StreamSubscriptionDemoHome({Key? key}) : super(key: key);

  @override
  _StreamSubscriptionDemoHomeState createState() => _StreamSubscriptionDemoHomeState();
}

class _StreamSubscriptionDemoHomeState extends State<StreamSubscriptionDemoHome> {
  /// 创建Stream接收数据
  Stream<String> stream = Stream.fromFuture(_feathData());
  String s = "";

  // 流的事件订阅
  late StreamSubscription streamSubscription;

  String streamStatus = "正常";

  @override
  void initState() {
    super.initState();
    streamSubscription = stream.listen(_onData,
        onError: _onError, onDone: _onDone, cancelOnError: false);
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Stream 基本使用"),
      ),
      body: Container(
        margin: EdgeInsets.only(left: 15, right: 15),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              height: 15,
            ),
            Text(
              "流数据: $s",
              style: Theme.of(context).textTheme.headline6,
            ),
            Text(
              "功能列表:",
              style: Theme.of(context).textTheme.subtitle1,
            ),
            Text(
              "1. 基本使用",
              style: Theme.of(context).textTheme.bodyText1,
            ),
            Text(
              "2. 事件订阅",
              style: Theme.of(context).textTheme.bodyText1,
            ),
            SizedBox(
              height: 15,
            ),
            Text(
              "Stream状态: $streamStatus",
              style: Theme.of(context).textTheme.subtitle1,
            ),
            SizedBox(
              height: 15,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                FlatButton(
                  onPressed: _pauseStream,
                  child: Text("pause"),
                  color: Colors.yellowAccent,
                ),
                FlatButton(
                  onPressed: _resumeStream,
                  child: Text("resume"),
                  color: Colors.green,
                ),
                FlatButton(
                  onPressed: _cancelStream,
                  child: Text("cancel"),
                  color: Colors.lightBlue,
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  /// 异步获取数据
  static Future<String> _feathData() async {
    await Future.delayed(Duration(seconds: 10));
    return "Hello Stream ~!";
    // throw "数据错误...";
  }

  /// 数据处理完成
  _onDone() {
    log("流已完成");
  }

  /// 有数据时回调
  void _onData(String event) {
    log("流数据： $event");
    setState(() {
      s = event;
    });
  }

  /// 出现错误
  _onError(error) {
    log("出现错误:$error");
  }

  void _pauseStream() {
    log("暂停Stream");
    streamSubscription.pause();
    setState(() {
      streamStatus = "pause";
    });
  }

  void _resumeStream() {
    log("继续Stream");
    streamSubscription.resume();
    setState(() {
      streamStatus = "resume";
    });
  }

  /// 取消再继续，流是不会继续往下走的
  void _cancelStream() {
    log("取消Stream");
    streamSubscription.cancel();
    setState(() {
      streamStatus = "cancel";
    });
  }
}
